<template>
  <div class="profile-page">
    <!-- 个人信息部分 -->
    <div class="profile-header">
      <el-avatar
          :src="user.avatarUrl || defaultAvatar"
          size="large"
          class="avatar"
      ></el-avatar>
      <div class="user-info">
        <h2>{{ user.stu_name||user.tch_name }}</h2>
        <el-button
            v-if="this.$route.query.profileuser_id != this.$route.query.user_id"
            :disabled="isFollowing === null"
            type="primary"
            size="medium"
            :style="{ maxWidth: '80px', padding: '4px 12px', fontSize: '14px' }"
            @click="toggleFollow"
        >
          {{ isFollowing === null ? "加载中..." : isFollowing ? "已关注" : "关注" }}
        </el-button>
        <el-button
            v-if="this.$route.query.profileuser_id == this.$route.query.user_id"
            type="primary"
            size="medium"
            :style="{ maxWidth: '80px', padding: '4px 12px', fontSize: '14px' }"
            @click="showFollowerList"
        >
          关注列表
        </el-button>

        <el-dialog
            title="关注列表"
            v-model="isDialogVisible"
            width="400px"
            @close="handleDialogClose"
        >
          <!-- 关注列表 -->
          <div>
            <div v-if="followers.length">
              <ul class="followers-list">
                <li
                    v-for="(follower, index) in followers"
                    :key="index"
                    class="follower-item"
                    @click="goToProfile(follower.user_id)"
                >
                  <el-avatar>{{ follower.username ? follower.username.charAt(0) : "?" }}</el-avatar>
                  <span class="follower-name">{{ follower.username || "未知用户" }}</span>
                </li>
              </ul>
            </div>
            <div v-else>
              <p>没有关注的人</p>
            </div>
          </div>

          <span slot="footer" class="dialog-footer">
    <el-button @click="isDialogVisible = false">关闭</el-button>
  </span>
        </el-dialog>
      </div>
    </div>
    <!-- 主体内容部分 -->
    <div class="profile-content">
      <!-- 侧边栏 -->
      <el-menu
          class="side-menu"
          :default-active="activeMenu"
          @select="handleMenuSelect"
          style="width: 200px"
      >
        <el-menu-item index="posts">发布的帖子</el-menu-item>
        <el-menu-item index="favorites">收藏的帖子</el-menu-item>
      </el-menu>

      <!-- 内容区 -->
      <div class="content-area">
        <!-- 发布的帖子 -->
        <div v-if="activeMenu === 'posts'" class="posts-list">
          <h3 v-if="userPosts.length">发布的帖子</h3>
          <p v-else>暂无发布的帖子</p>
          <div v-for="post in userPosts" :key="post.post_id" class="post-item">
            <h4>{{ post.title }}</h4>
            <p>{{ post.description }}</p>
            <el-button type="text" @click="goToPostDetail(post.post_id)">查看帖子</el-button>
          </div>
        </div>

        <!-- 收藏的帖子 -->
        <div v-if="activeMenu === 'favorites'" class="posts-list">
          <h3 v-if="favoritePosts.length">收藏的帖子</h3>
          <p v-else>暂无收藏的帖子</p>
          <div v-for="post in favoritePosts" :key="post.post_id" class="post-item">
            <h4>{{ post.title }}</h4>
            <p>{{ post.description }}</p>
            <el-button type="text" @click="goToPostDetail(post.post_id)">查看帖子</el-button>
          </div>
        </div>
      </div>
    </div>
    </div>
</template>

<script>
import axios from 'axios';
import { BASE_URL } from '@/config';

export default {
  data() {
    return {
      user: {},
      isFollowing: null,
      userPosts: [], // 用户发布的帖子
      favoritePosts: [], // 用户收藏的帖子
      activeMenu: "posts", // 当前激活的菜单项，默认显示发布的帖子
      activeFavoritePosts: [], // 当前收藏夹的帖子列表
      isDialogVisible: false, // 控制对话框显示
      followers: [], // 存储关注列表
      defaultAvatar: 'https://www.gravatar.com/avatar/?d=mp', // 默认头像
    };
  },
  created() {
    this.fetchUserInfo(); // 获取用户信息
    this.fetchUserPosts(); // 获取用户发布的帖子
    this.fetchFavoritePosts(); // 获取用户收藏的帖子
    this.checkFollowStatus(); // 检查关注状态
  },
  methods: {
    // 获取用户信息


    async fetchUserInfo(){
      try {
        let response;
        console.log("路由2：", this.$route.query.profileuser_id)
        const user_id = this.$route.query.profileuser_id; // 正确获取路由中的 profileuser_id
        console.log("个人主页 user_id:", user_id);


        // 判断用户类型：学号长度为4的是老师，为8的是学生
        if (user_id.length === 4) {
          // 教师信息
          response = await axios.post(`${BASE_URL}/teacher/showTeacherMsg`, { tch_id: user_id });
          const data = response.data.data || {};
          this.user = {
            role: data.tch_title || '', // 教师职称
            phone: '', // 可扩展属性
            tch_name: data.tch_name || '',
            tch_email: data.tch_email || '',
            department: data.tch_department || '',
          };
          console.log(this.user);
        } else if (user_id.length === 8) {
          // 学生信息
          response = await axios.post(`${BASE_URL}/student/showStudentMsg`, { stu_id: user_id });
          const data = response.data.data || {};
          this.user = {
            role: '学生', // 固定角色
            phone: '', // 可扩展属性
            stu_name: data.stu_name || '',
            stu_email: data.stu_email || '',
            department: data.stu_department || '',
          };
        } else {
          throw new Error('用户名长度不符合要求');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    async checkFollowStatus() {
      try {
        const profileuser_id = this.$route.query.profileuser_id;
        const userId = window.sessionStorage.getItem('userId');

        if (!userId || !profileuser_id) {
          this.isFollowing = false;
          return;
        }

        const response = await axios.post(`${BASE_URL}/posts/isFollow`, {
          follower_id: userId,
          followed_id: profileuser_id,
        });

        if (response.data.code === 200) {
          this.isFollowing = !!response.data.data; // 确保布尔值
        } else {
          this.isFollowing = false;
        }
      } catch (error) {
        console.error('检查关注状态失败:', error.message);
        this.isFollowing = false;
      }
    },


    // 获取发布的帖子
    async fetchUserPosts() {
      try {
        const user_id = this.$route.query.profileuser_id;
        const response = await axios.post(`${BASE_URL}/posts/myPost`, { stu_id:user_id });
        this.userPosts = response.data.data || [];
      } catch (error) {
        console.error("获取用户发布的帖子失败:", error.message);
      }
    },

    // 获取收藏的帖子
    async fetchFavoritePosts() {
      try {
        const user_id = this.$route.query.profileuser_id;
        const response = await axios.post(`${BASE_URL}/posts/favoriteList`, { stu_id:user_id });
        this.favoritePosts = response.data.data || [];
      } catch (error) {
        console.error("获取用户收藏的帖子失败:", error.message);
      }
    },

    toggleFollow() {
      const profileuser_id = this.$route.query.profileuser_id;
      const userId = window.sessionStorage.getItem('userId');

      if (!userId) {
        this.$message.error('用户未登录');
        return;
      }

      const apiUrl = this.isFollowing
          ? `${BASE_URL}/posts/unfollow`
          : `${BASE_URL}/posts/follow`;

      axios
          .post(apiUrl, {
            follower_id: userId,
            followed_id: profileuser_id,
          })
          .then((response) => {
            if (response.data.code === 200) {
              this.checkFollowStatus(); // 重新获取状态
              this.$message.success(this.isFollowing ? '取消关注成功' : '关注成功');
            } else {
              this.$message.error(this.isFollowing ? '取消关注失败' : '关注失败');
            }
          })
          .catch(() => {
            this.$message.error(this.isFollowing ? '取消关注失败' : '关注失败');
          });
    },


    showFollowerList() {
      this.isDialogVisible = true;
      this.fetchFollowers(); // 获取关注列表
    },
    // 处理菜单切换
    handleMenuSelect(key) {
      this.activeMenu = key;
    },
    // 获取关注数据（示例使用静态数据，可替换为 API 调用）
    async fetchFollowers() {
      try {

        const profileuser_id = this.$route.query.profileuser_id;

        // 模拟 API 调用，实际替换为后端接口
        const response = await axios.post(`${BASE_URL}/posts/followList`, { follower_id: profileuser_id });

        if (response.data.code === 200) {
          this.followers = response.data.data || [];
        } else {
          this.$message.error(response.data.message || "获取关注列表失败");
        }
      } catch (error) {
        console.error("获取关注列表失败:", error);
        this.$message.error("网络错误，无法获取关注列表");
      }
    },
    // 关闭对话框时清理逻辑
    handleDialogClose() {
      this.isDialogVisible = false;
    },
    goToProfile(profileuser_id) {
      this.$router.push({
        name: "ProfilePage",
        query: { profileuser_id, user_id: window.sessionStorage.getItem("userId") },
      }).then(() => {
        location.reload(); // 刷新页面
      });
    },
    goToPostDetail(postId) {
      if (!postId) {
        console.error('postId is missing');
        return;
      }
      this.$router.push(`/PostDetail/${postId}`)
    },
  }
};
</script>


<style scoped>.profile-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, #eaf8fc, #d9e7f3);
  color: #2c3e50;
  padding: 20px;
  box-sizing: border-box;
  font-family: "Arial", sans-serif;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #4cafef;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-info h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #34495e;
}

.el-button {
  border-radius: 6px;
}

.profile-content {
  display: flex;
  gap: 20px;
}

.side-menu {
  background: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.el-menu {
  border: none;
  font-size: 16px;
}

.content-area {
  flex: 1;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.posts-list h3 {
  font-size: 20px;
  color: #4cafef;
  margin-bottom: 10px;
}

.post-item {
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
  transition: all 0.3s ease-in-out;
}

.post-item:hover {
  transform: translateX(5px);
}

.post-item h4 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #34495e;
}

.post-item p {
  margin: 5px 0;
  color: #7f8c8d;
  font-size: 14px;
}

.post-item .el-button {
  color: #4cafef;
  font-size: 14px;
}

.no-data {
  text-align: center;
  font-size: 16px;
  color: #aaa;
  margin-top: 20px;
}

.followers-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.follower-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
  transition: all 0.3s;
}

.follower-item:hover {
  background: #f0f4f8;
}

.follower-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.follower-name {
  font-size: 16px;
  color: #2c3e50;
}
</style>

